package cn.wj.school.cloud.security.interceptor;

import cn.wj.school.cloud.dto.PrivilegeCheckDTO;
import cn.wj.school.cloud.dto.SyUserDTO;
import cn.wj.school.cloud.exception.ServiceInvokeException;
import cn.wj.school.cloud.service.ResourceService;
import cn.wj.school.cloud.utils.SecurityUtils;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.google.common.net.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;

/**
 * @Author: yueding
 * @Description: 自定义权限拦截器
 * @Date: Created in 10:53 2018/5/17
 * @Modified By: mvc拦截器添加 Copyright(c) cai-inc.com
 */
@Slf4j
@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ResourceService resourceService;

    private String loginDomain = "";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        String requestURI = request.getRequestURI().substring(request.getContextPath().length());
        String method = request.getMethod().toLowerCase();
        SyUserDTO user = SecurityUtils.getCurrentUser();
        if (user != null && "admin".equals(user.getCard())) {
            return true;
        }
        PrivilegeCheckDTO check = resourceService.isResourcePermit(user, requestURI);
        /* 用户未登录 */
        if (check.getErrorType() == PrivilegeCheckDTO.ErrorType.UNAUTHENTICATED.toNumber()) {
            log.debug("ACCESS_LOG[][][]web-auth[]用户认证[]授权拦截[]用户未登录[]path={},method={},user={}", requestURI, method,
                    user);
            redirectToLogin(request, response);
            return false;
        }

        /* 用户未授权 */
        if (check.getErrorType() == PrivilegeCheckDTO.ErrorType.UNAUTHORIZED.toNumber()) {
            log.warn("ACCESS_LOG[][][]web-auth[]用户认证[]授权拦截[]用户未授权[]path={},method={},user={}", requestURI, method,
                    user);
            throw ServiceInvokeException.newException(HttpStatus.FORBIDDEN, "用户未授权");
        }
        return true;
    }

    private void redirectToLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        if (isAjaxRequest(request)) {
            throw ServiceInvokeException.newException(HttpStatus.UNAUTHORIZED, "用户未登录");
        }
        String currentUrl = request.getRequestURL().toString();

        if (!Strings.isNullOrEmpty(request.getQueryString())) {
            currentUrl = currentUrl + "?" + request.getQueryString();
        }
        UriComponents uriComponents =
                UriComponentsBuilder.fromUriString(loginDomain + "/login?target={target}").build();
        URI uri = uriComponents.expand(currentUrl).encode().toUri();
        request.getSession();
        response.sendRedirect(uri.toString());
    }

    private boolean isAjaxRequest(HttpServletRequest request) {
        return Objects.equal(request.getHeader(HttpHeaders.X_REQUESTED_WITH), "XMLHttpRequest");
    }

}
